<template>
  <div>
    <div id="container"></div>
    <!-- <img src="./draw01.png"> -->
  </div>
</template>

<script>
import { canvasIcon } from './CanvasDrawer.js';
import { v4 as uuidv4 } from 'uuid';

export default {
  data() {
    return {
      layersData: [],
      map: null,
      opt: null,
      canvasLayers: [],

    }
  },
  props: {
    getMapList: {
      type: Array,
    }
  },
  watch: {
    getMapList(value) {
      console.log("getMapList:",this.getMapList)
      this.initMap();
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    generateUUIDWithoutHyphens() {
      const uuid = uuidv4();
      return uuid.replace(/-/g, ''); // 使用正则表达式去除连字符
    },
    layersDataFor() {
      const self = this;
      self.layersData.forEach((layerData, index) => {
        const { name, centerLongitude, centerLatitude, width, height } = layerData;
        const canvas = canvasIcon(layerData, self.generateUUIDWithoutHyphens(), index === self.opt);
        const calculatedBounds = this.calculateBounds(centerLongitude, centerLatitude, width, height);
        const canvasLayer = new AMap.CanvasLayer({
          canvas: canvas,
          bounds: new AMap.Bounds(
            calculatedBounds[0], calculatedBounds[1]
          ),
          zIndex: index === self.opt ? 999 : 998, // 设置zIndex，确保CanvasLayer在其他图层之上
        });

        // 获取CanvasLayer的canvas元素
        const canvasElement = canvasLayer.getCanvas();

        // 将点击事件直接添加到canvas元素上

        //右键按钮
        canvasElement.addEventListener('contextmenu', event => {
          // // console.log(`点击事件`+ index);
          // self.opt = index;
          // // 清除原有的Canvas图层
          // self.canvasLayers.forEach(layer => {
          //   layer.setMap(null);
          // });
          // // 移除原有的Canvas元素
          // self.canvasLayers.forEach(layer => {
          //   const canvasElementToRemove = layer.getCanvas();
          // });
          // // 清空canvasLayers数组
          // self.canvasLayers = [];
          // // 重新绘制图层
          // self.layersDataFor();
        });

        //左键按钮
        canvasElement.addEventListener('click', event => {
          console.log(`点击事件`+ this.getMapList[index]);
          self.opt = index;
          // 清除原有的Canvas图层
          self.canvasLayers.forEach(layer => {
            layer.setMap(null);
          });
          // 移除原有的Canvas元素
          self.canvasLayers.forEach(layer => {
            const canvasElementToRemove = layer.getCanvas();
          });
          // 清空canvasLayers数组
          self.canvasLayers = [];
          // 重新绘制图层
          self.layersDataFor();
          this.$emit("openDetail", this.getMapList[index]);
        });



        // 将CanvasLayer添加到数组中
        self.canvasLayers.push(canvasLayer);
      });

      // 将每个CanvasLayer添加到地图上
      self.canvasLayers.forEach(layer => {
        layer.setMap(self.map);
      });
    },
    initMap() {
      const self = this;

      self.layersData = self.transformData(self.getMapList)
      // console.log(self.layersData);
      self.map = new AMap.Map('container', {
        // center: [125.546178, 45.728374],
        zooms: [1, 20],
        zoom: 9
      });
      AMap.plugin(["AMap.ControlBar"], function () {
        var bar = new AMap.ControlBar();
        self.map.addControl(bar);
      });

      // 获取当前用户位置
      navigator.geolocation.getCurrentPosition(function (position) {
        // 获取到用户位置后设置地图中心点
        const { latitude, longitude } = position.coords;
        self.map.setCenter([longitude, latitude]);
      }, function (error) {
        console.error('无法获取用户位置:', error);
        // 如果无法获取用户位置，您可能需要设置一个默认的中心点
        self.map.setCenter([125.546178, 45.728374]);
      });

      self.layersDataFor()
    },
    //计算中心位置
    calculateBounds(centerLongitude, centerLatitude, width, height) {
      // 经度和纬度的差值
      var deltaLongitude = width / 2 / 111.32;  // 1 经度差值对应的距离（大致值）
      var deltaLatitude = height / 2 / (111.32 * Math.cos((centerLatitude * Math.PI) / 180));  // 1 纬度差值对应的距离（大致值）
      // 计算左上角和右下角的经纬度坐标
      var bounds = [
        new AMap.LngLat(centerLongitude - deltaLongitude, centerLatitude + deltaLatitude),  // 左上角
        new AMap.LngLat(centerLongitude + deltaLongitude, centerLatitude - deltaLatitude)   // 右下角
      ];

      const arr = [
        [bounds[0].lng, bounds[0].lat],
        [bounds[1].lng, bounds[1].lat],
      ]
      return arr;
    },
    //转换数组
    transformData(data) {
      return data.map(item => {
        let centerLongitude, centerLatitude;

        if (item.radioStationGps) {
          const [longitude, latitude] = item.radioStationGps.split('|');
          centerLongitude = parseFloat(longitude);
          centerLatitude = parseFloat(latitude);
          console.log(longitude);
          console.log(longitude);
        }
        return {
          ...item,
          centerLongitude,
          centerLatitude,
          width: 4,
          height: 2
        };
      });
    }


  }
};
</script>

<style scoped>
html,
body,
#container {
  width: 100%;
  height: 100%;
}
</style>
